package com.hbnu.service;

import com.hbnu.dao.UserDao;
import com.hbnu.pojo.MyThread;
import com.hbnu.pojo.Play;
import com.hbnu.pojo.User;

import java.io.BufferedReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class roomThread implements Runnable{
    private Map<Socket, String> partUser;
    private ConcurrentHashMap<Socket,PrintWriter> allOut;
    private ConcurrentHashMap<Socket,BufferedReader> allInput;
    private ConcurrentHashMap<Socket, MyThread> waitingThread;
    private UserDao userDao=new UserDao();

    public roomThread(Map<Socket, String> partUser, ConcurrentHashMap<Socket, PrintWriter> allOut, ConcurrentHashMap<Socket, BufferedReader> allInput, ConcurrentHashMap<Socket, MyThread> waitingThread) {
        this.partUser = partUser;
        this.allOut = allOut;
        this.allInput = allInput;
        this.waitingThread = waitingThread;
    }

    @Override
    public void run() {
        try {
            StringBuilder stringBuilder = new StringBuilder();
            StringBuilder userNameAll = new StringBuilder();
            for (String name:partUser.values()) {
                stringBuilder.append(name+" ");
                userNameAll.append(name);
                User user=userDao.findUserByusername(name);
                if (user.getSegment()<11) {
                    stringBuilder.append("小白"+user.getSegment()+"星");
                } else if (user.getSegment()>10&& user.getSegment()<21) {
                    stringBuilder.append("赌鬼"+(user.getSegment()-10)+"星");
                }else if (user.getSegment()>20&& user.getSegment()<31) {
                    stringBuilder.append("赌王"+(user.getSegment()-20)+"星");
                }else if (user.getSegment()>30&& user.getSegment()<41) {
                    stringBuilder.append("赌圣"+(user.getSegment()-30)+"星");
                }else {
                    stringBuilder.append("赌神"+(user.getSegment()-40)+"星");
                }
                stringBuilder.append(",");
                userNameAll.append(",");
            }
            stringBuilder.deleteCharAt(stringBuilder.length()-1);
            userNameAll.deleteCharAt(userNameAll.length()-1);
            int i = 1;
            List<Play> playList = new ArrayList<>();
            List<Play> playSpare = new ArrayList<>();
            for (Socket s:partUser.keySet()) {
                Play play =new Play(i,partUser.get(s),s,0,new Random().nextInt(6)+1,allOut.get(s),allInput.get(s),1,null);
                play.getOut().println("匹配成功！");
                play.getOut().println("您是"+(i++)+"号玩家");
                play.getOut().println("本局玩家有："+stringBuilder);
                playList.add(play);
                playSpare.add(play);
            }
            while (playList.size()>1) {
                List<String> total = new ArrayList<>();
                String[] nums={"J","Q","K","A"};
                String[] color={"♣","♦","♠","♥"};
                for (String n:nums) {
                    for (String c :color) {
                        total.add(c+n);
                    }
                }
                total.add("King");
                total.add("Queen");
                total.add("demon");
                total.add("devil");
                String flag= (total.get(new Random().nextInt(16))).substring(1);
                Collections.shuffle(total);
                for (Play p:playList) {
                    p.getOut().println("本局liar牌是："+flag);
                }
                List<String> playOne = new ArrayList<>();
                List<String> playTwo = new ArrayList<>();
                List<String> playThree = new ArrayList<>();
                List<String> playFour = new ArrayList<>();
                for (int j = 0; j < total.size(); j++) {
                    if (j % 4 == 0) {
                        playOne.add(total.get(j));
                    }else if (j % 4 == 1) {
                        playTwo.add(total.get(j));
                    }else if (j % 4 == 2) {
                        playThree.add(total.get(j));
                    }
                    else if (j % 4 == 3) {
                        playFour.add(total.get(j));
                    }
                }
                for (Play p:playList) {
                    if (p.getId() == 1) {
                        p.setPlayBoard(playOne);
                        p.getOut().println("你的手牌是："+playOne);
                    } else if (p.getId() == 2) {
                        p.setPlayBoard(playTwo);
                        p.getOut().println("你的手牌是："+playTwo);
                    }else if (p.getId() == 3) {
                        p.setPlayBoard(playThree);
                        p.getOut().println("你的手牌是："+playThree);
                    }else {
                        p.setPlayBoard(playFour);
                        p.getOut().println("你的手牌是："+playFour);
                    }
                }
                    List<Play> playEmpty = new ArrayList<>();
                    for (Play p:playList) {
                        p.getOut().println("现在轮到"+playList.get(0).getId()+"号玩家出牌");
                    }
                    playList.get(0).getOut().println("请选择出哪几张牌（数字从1开始,逗号间隔）");
                    String[] num = playList.get(0).getInput().readLine().split(",");
                    StringBuilder sb = new StringBuilder();
                    List<String> temp = new ArrayList<>();
                    List<String> q =playList.get(0).getPlayBoard();
                    Arrays.sort(num,Comparator.reverseOrder());
                    for (String s:num) {
                        temp.add(q.get(Integer.parseInt(s) - 1));
                        q.remove(Integer.parseInt(s)-1);
                        sb.append("□");
                        sb.append(" ");
                    }
                    playList.get(0).setPlayBoard(q);
                    for (Play p:playList) {
                        p.getOut().println("玩家"+playList.get(0).getName()+"出了"+num.length+"张牌："+sb);
                    }
                    if (playList.get(0).getPlayBoard().isEmpty()) {
                        playEmpty.add(playList.get(0));
                    }
                    for (int k = 1; ; k++) {
                        int count = 0;
                        if (k == playList.size()) {
                            k=0;
                        }
                        if (playList.get(k).getPlayBoard().isEmpty()) {
                            continue;
                        }
                        for (Play p:playList) {
                            if (p.getPlayBoard().isEmpty()) {
                                count++;
                            }
                        }
                        int n = k-1;
                        while (playList.get(n).getPlayBoard().isEmpty()){
                            n--;
                            if (n <0) {
                                n=playList.size()-1;
                            }
                        }
                        if (n == k) {
                            for (int j = 0; j < playList.size(); j++) {
                                if (playList.get(j).getId()==playEmpty.get(playEmpty.size()-1).getId()) {
                                    n=j;
                                    break;
                                }
                            }
                        }
                        for (Play p:playList) {
                            p.getOut().println("轮到"+playList.get(k).getId()+"号玩家"+playList.get(k).getName()+"做选择");
                        }
                        String choice = "2";
                        if (count == (playList.size()-1)) {
                            for (Play p:playList) {
                                p.getOut().println("玩家"+playList.get(k).getName()+"只能掀"+playList.get(n).getName());
                            }
                        }else {
                            playList.get(k).getOut().println("请选择：1、掀他 2、出牌");
                            choice=playList.get(k).getInput().readLine();
                        }
                        if (choice.equals("1")||count==(playList.size()-1)) {
                            boolean f = true;
                            for (String s:temp) {
                                if (!s.equals("King")&&!s.equals("Queen")&&!s.equals("demon")&&!s.equals("devil")&&!s.contains(flag)) {
                                    f=false;
                                    break;
                                }
                            }
                            for (Play p:playList) {
                                p.getOut().println("玩家"+playList.get(k).getName()+"选择掀牌");
                                p.getOut().println("玩家"+playList.get(n).getName()+"的牌是："+temp);
                            }
                            if (f) {
                                Integer shoot =playList.get(k).getShoots()+1;
                                playList.get(k).setShoots(shoot);
                                for (Play p:playList) {
                                    p.getOut().println("玩家"+playList.get(k).getName()+"开了:"+shoot+"/6"+"枪");
                                }
                                if (shoot==playList.get(k).getDestiny()) {
                                    for (Play p:playSpare) {
                                        if (p.getId() == playList.get(k).getId()) {
                                            p.getOut().println("你寄了");
                                        }else {
                                            p.getOut().println("玩家" + playList.get(k).getName() + "寄了");
                                        }
                                    }
                                    playList.remove(k);
                                }
                            }else {
                                Integer shoot =playList.get(n).getShoots()+1;
                                playList.get(n).setShoots(shoot);
                                for (Play p:playList) {
                                    p.getOut().println("玩家"+playList.get(n).getName()+"开了:"+shoot+"/6"+"枪");
                                }
                                if (shoot==playList.get(n).getDestiny()) {
                                    for (Play p:playSpare) {
                                        if (p.getId() == playList.get(n).getId()) {
                                            p.getOut().println("你寄了");
                                        }else {
                                            p.getOut().println("玩家" + playList.get(n).getName() + "寄了");
                                        }
                                    }
                                    playList.remove(n);
                                }
                            }
                            temp.clear();
                            break;
                        }else {
                            temp.clear();
                            playList.get(k).getOut().println("您的手牌是:"+playList.get(k).getPlayBoard());
                            playList.get(k).getOut().println("请选择出哪几张牌（数字从1开始,逗号间隔）");
                            num = playList.get(k).getInput().readLine().split(",");
                            sb= new StringBuilder();
                            List<String> t = playList.get(k).getPlayBoard();
                            Arrays.sort(num,Comparator.reverseOrder());
                            for (String s:num) {
                                temp.add(t.get(Integer.parseInt(s) - 1));
                                t.remove(Integer.parseInt(s)-1);
                                sb.append("□");
                                sb.append(" ");
                            }
                            playList.get(k).setPlayBoard(t);
                            if (playList.get(k).getPlayBoard().isEmpty()) {
                                playEmpty.add(playList.get(k));
                            }
                            for (Play p:playList) {
                                p.getOut().println("玩家"+playList.get(k).getName()+"出了"+num.length+"张牌:"+sb);
                            }
                        }
                    }
            }
            for (Play p:playSpare) {
                if (p.getId() == playList.get(0).getId()) {
                    p.getOut().println("victory");
                    userDao.insertRecord(p.getName(), String.valueOf(userNameAll),"victory");
                    userDao.updateSegmentByName(p.getName(),1);
                }else{
                    p.getOut().println("defeat");
                    userDao.insertRecord(p.getName(), String.valueOf(userNameAll),"defeat");
                    userDao.updateSegmentByName(p.getName(),-1);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("客户端连接已断开");
            Thread thread = Thread.currentThread();
            thread.stop();
        } finally {
            for (Socket s:partUser.keySet()) {
                Thread thread =waitingThread.get(s).getThread();
                if (thread != null) {
                    waitingThread.get(s).getLock().lock();
                    waitingThread.get(s).getCondition().signal();
                    waitingThread.get(s).getLock().unlock();
                }
            }
        }
    }
}
